package logx

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"io"
	"os"
	"sync"
	"time"
)

var LogrusObj *logrus.Logger

// 文件创建锁
var (
	LogFileLock       = sync.RWMutex{}
	LogFile           *os.File
	LogFileInfo       os.FileInfo
	LogFileCreateTime time.Time
)

// 初始化日志组件
func InitLog() (close func() error) {
	var err error
	LogFile, err = NewLogFile()
	if err != nil {
		panic(errors.Wrap(err, "[LOGRUS]"))
	}

	// 日志文件信息初始化
	LogFileInfo, err = LogFile.Stat()
	if err != nil {
		panic(errors.Wrap(err, "[LOGRUS]"))
	}
	LogFileCreateTime = LogFileInfo.ModTime()

	// 实例化
	LogrusObj = logrus.New()
	// 日志等级
	var logLevel logrus.Level
	switch gin.Mode() {
	case gin.DebugMode:
		logLevel = logrus.DebugLevel
		break
	case gin.ReleaseMode:
		logLevel = logrus.InfoLevel
		break
	default:
		logLevel = logrus.DebugLevel
	}
	LogrusObj.SetLevel(logLevel)

	// 设置输出
	LogrusObj.SetOutput(io.MultiWriter(LogFile, os.Stdout))
	LogrusObj.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: "2006/01/02 15:04:05",
	})

	// Fatal 输出 os.Exit(1)
	logrus.RegisterExitHandler(func() {
		LogrusObj.Errorln("something serious problem make shutdown")
	})

	return func() error {
		return LogrusObj.Writer().Close()
	}
}

// 获取写入文件名
func todayFilename() (string, error) {
	wd, err := os.Getwd()
	if err != nil {
		return "", errors.Wrap(err, "get workdir failure")
	}
	path := wd + "/logs/" + time.Now().Format("2006-01")
	err = os.MkdirAll(path, os.ModePerm)
	if err != nil {
		return "", errors.Wrap(err, "make workdir failure")
	}
	day := time.Now().Format("02")

	return path + "/" + day + ".log", nil
}

// 获取文件对象
func NewLogFile() (*os.File, error) {
	filename, err := todayFilename()
	if err != nil {
		return nil, errors.Wrap(err, "can't get filename")
	}
	file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return nil, errors.Wrap(err, "can't open file"+filename)
	}
	return file, nil
}
